package com.suman.bbcticker.parser;

import java.net.URL;
import java.net.URLConnection;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Xml;

import com.suman.bbcticker.FeedItem;
import com.suman.bbcticker.R;
import com.suman.bbcticker.RssFeed;

public class RssFeedHandler {
	private RssFeed rssFeed = new RssFeed();
	private FeedItem currentFeedItem;
	
	public RssFeed createFeed(URL url) {
		try {

			boolean inTitle = false;
			boolean inLink = false;
			boolean inDescription = false;
			boolean inItem = false;
			boolean inPubdate = false;

			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			factory.setValidating(false);
			XmlPullParser xpp = factory.newPullParser();
			xpp.setFeature(Xml.FEATURE_RELAXED, true);

			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(R.string.rssfeed_connecttimeout);
			conn.setReadTimeout(R.string.rssfeed_readtimeout);

			xpp.setInput(conn.getInputStream(), "utf-8");
			int eventType = xpp.getEventType();

			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					String name = xpp.getName();

					if (name.trim().equals("title")) {
						inTitle = true;
					} else if (name.trim().equals("description")) {
						inDescription = true;
					} else if (name.trim().equals("link")) {
						inLink = true;
					} else if (name.trim().equals("pubDate")) {
						inPubdate = true;
					} else if (name.trim().equals("item")) {
						inItem = true;
						currentFeedItem = new FeedItem();
					}

				} else if (eventType == XmlPullParser.END_TAG) {
					String name = xpp.getName();
					if (name.trim().equals("title")) {
						inTitle = false;
					} else if (name.trim().equals("description")) {
						inDescription = false;
					} else if (name.trim().equals("link")) {
						inLink = false;
					} else if (name.trim().equals("pubDate")) {
						inPubdate = false;
					} else if (name.trim().equals("item")) {
						inItem = false;
						rssFeed.addFeedItem(currentFeedItem);
					}

				} else if (eventType == XmlPullParser.TEXT) {
					String chars = xpp.getText();
					if (inItem) {
						if (inTitle) {
							inTitle = false;
							currentFeedItem.setTitle(chars);
						} else if (inLink) {
							inLink = false;
							currentFeedItem.setLink(chars);
						} else if (inPubdate) {
							inPubdate = false;
							currentFeedItem.setPubdate(chars);
						} else if (inDescription) {
							inDescription = false;
							currentFeedItem.setDescription(chars);
						}

					}

				}
				eventType = xpp.next();
			}

			return rssFeed;
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return null;

	}

}
